package com.hk.blog.controller;

import com.hk.blog.domain.CategoryInfo;
import com.hk.blog.service.CategoryInfoService;
import com.hk.commons.JsonResult;
import com.hk.commons.query.Order;
import com.hk.commons.query.QueryModel;
import com.hk.core.authentication.api.SecurityContextUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * @author Kevin
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("category")
public class CategoryInfoController {

    private final CategoryInfoService categoryInfoService;

    @GetMapping
    public JsonResult<?> findAll() {
        return JsonResult.success(categoryInfoService.findByUserId(
                        SecurityContextUtils.getPrincipal().getUserId(), Order.desc("lastModifiedDate"))
                .stream()
                .map(item -> Map.of("value", Objects.requireNonNull(item.getId()),
                        "label", item.getCategoryName()))
                .collect(Collectors.toList()));
    }

    @GetMapping(path = "{id}")
    public JsonResult<?> get(@PathVariable Long id) {
        return JsonResult.success(categoryInfoService.findById(id).orElse(null));
    }

    @PostMapping(path = "delete")
    public JsonResult<Boolean> deleteById(@RequestParam Long id) {
        categoryInfoService.deleteById(id);
        return JsonResult.success(true);
    }

    @PostMapping(path = "page")
    public JsonResult<?> findPage(@RequestBody QueryModel<CategoryInfo> queryModel) {
        if(queryModel.getOrders().isEmpty()){
            queryModel.addOrders(Order.desc("createdDate"));
        }
        queryModel.getParam().setUserId(SecurityContextUtils.getPrincipal().getUserId());
        return JsonResult.success(categoryInfoService.queryForPage(queryModel));
    }

    @PostMapping(path = "save")
    public JsonResult<?> saveOrUpdate(@RequestBody CategoryInfo categoryInfo) {
        categoryInfoService.insertOrUpdate(categoryInfo);
        return JsonResult.success(true);
    }
}
